//
//  DEMOSecondViewController.m
//  RESideMenuExample
//
//  Created by Roman Efimov on 10/10/13.
//  Copyright (c) 2013 Roman Efimov. All rights reserved.
//

#import "HQFavoriteViewController.h"
#import "HQViewController.h"
#import "HQCollectionViewCell.h"
#import "HQNavigationController.h"
#import "HQDetailViewController.h"
#import "HQZhou.h"
#import "UIView+Extension.h"
#import "UIButton+Extension.h"


#define IS_IPHONE5 (([[UIScreen mainScreen] bounds].size.height == 568) ? YES : NO)
#define IS_IPhone6 (667 == [[UIScreen mainScreen] bounds].size.height ? YES : NO)
#define IS_IPhone6plus (736 == [[UIScreen mainScreen] bounds].size.height ? YES : NO)


@interface HQFavoriteViewController () <UICollectionViewDataSource, UICollectionViewDelegate>

@property (strong, nonatomic)  UICollectionView *collectionView;

@property (nonatomic, strong) NSMutableArray *favoriteList;

@property (nonatomic, strong) UIButton *button;




@end

static NSString *favoriteID = @"favoriteID";

@implementation HQFavoriteViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	self.title = @"我的收藏";

    
    //添加左边按钮
    UIButton *leftButton = [UIButton buttonWithImage:@"nav_button_back" title:@"返回" font:15 setColorRed:0.798 green:0.613 blue:0.392];
    [leftButton addTarget:self action:@selector(presentLeftMenuViewController:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];

    
    //添加右边导航按钮
    UIButton *rightButton = [UIButton buttonWithImage:@"nav_button" title:@"主页" font:15 setColorRed:0.798 green:0.613 blue:0.392];
    [rightButton addTarget:self action:@selector(pushViewController:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    
    if (self.favoriteList.count == 0) {
        //没有收藏时候跳转主页
        UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        button.frame = CGRectMake(0, 84, 300, 44);
        button.x = (self.view.width - 300) * 0.5;
        button.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        [button setTitle:@"还没有收藏,点击返回米粥信息" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor colorWithRed:0.798 green:0.613 blue:0.392 alpha:1.000] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:19];
        [button setBackgroundColor:[UIColor colorWithWhite:0.800 alpha:1.000]];
        button.layer.cornerRadius = 10;
        button.layer.masksToBounds = YES;
        [button addTarget:self action:@selector(pushViewController:) forControlEvents:UIControlEventTouchUpInside];
        
        
        
        self.button = button;
        [self.view addSubview:button];

    }

    
    //背景
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"common_bg"]];
    
    [self prepareForUI];
}

//返回主页方法
- (void)pushViewController:(id)sender
{
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    HQViewController *viewController = [sb instantiateViewControllerWithIdentifier:@"main"];
    [self.navigationController pushViewController:viewController animated:YES];

}

/**********************************************/

//准备UI
- (void)prepareForUI{
    
//    NSLog(@"进入了准备UI");
    
    //设定参数
    UICollectionViewFlowLayout *layout =[[UICollectionViewFlowLayout alloc] init];
    
    layout.itemSize = CGSizeMake(150, 170);
    layout.sectionInset = UIEdgeInsetsMake(10, 5, 10, 5);
    
    if (IS_IPhone6) {
        layout.itemSize = CGSizeMake(170, 190);
        layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    }
    else if (IS_IPhone6plus) {
        layout.itemSize = CGSizeMake(190, 210);
        layout.sectionInset = UIEdgeInsetsMake(10, 15, 10, 15);
    }
    
    //    layout.itemSize = CGSizeMake(150, 170);
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 10;
    

    self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    self.collectionView.height -= 64;

    
    
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"common_bg"]];
    self.collectionView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"common_bg"]];
    
    //注册cell
    [self.collectionView registerNib:[UINib nibWithNibName:@"HQCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:favoriteID];

    
    //指定代理
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    
    [self.view addSubview:self.collectionView];
    
    [self.view bringSubviewToFront:self.button];
    
}

//数据源方法
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.favoriteList.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    HQCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:favoriteID forIndexPath:indexPath];
    HQZhou *zhou = self.favoriteList[indexPath.item];
    cell.zhou = zhou;
    
    //添加删除手势
    UILongPressGestureRecognizer *LG = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressAction:)];
    LG.minimumPressDuration = 1.0f;
    LG.view.tag = indexPath.item;
    [cell addGestureRecognizer:LG];
    
    
    return cell;
}

//collection代理方法

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    HQDetailViewController *detailVC = [[HQDetailViewController alloc] init];
    HQZhou *zhou = self.favoriteList[indexPath.item];
    detailVC.zhou = zhou;
    detailVC.fromVC = @"favoriteVC";
    HQNavigationController *nav = [[HQNavigationController alloc] initWithRootViewController:detailVC];
    
    [self presentViewController:nav animated:true completion:nil];
    
}

//触发删除提示
- (void)longPressAction:(UILongPressGestureRecognizer *)gesture {
    
    //    NSLog(@"长按了");
    if (gesture.state == UIGestureRecognizerStateBegan) {
        //        NSLog(@"开始触发长按操作");
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self deleteItem:gesture];
    }];
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"删除收藏" message:@"你确定删除个收藏吗?" preferredStyle:UIAlertControllerStyleAlert];
    
    [alertController addAction:cancelAction];
    [alertController addAction:sureAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
    
    }
    else if (gesture.state == UIGestureRecognizerStateEnded) {
        //        NSLog(@"长按结束");
    }
}


//删除动作
- (void)deleteItem:(UILongPressGestureRecognizer *)LG {

        
        //删除缓存
        [self.favoriteList removeObjectAtIndex:LG.view.tag];
        
        //删除归档文件的数据
        NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        
        NSString *filePath = [docPath stringByAppendingPathComponent:@"favorite.archieve"];
        
        NSMutableArray *templeArr = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
        
        [templeArr removeObjectAtIndex:LG.view.tag];
        
        [NSKeyedArchiver archiveRootObject:templeArr toFile:filePath];
        
        
        
        //删除显示的cell
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:LG.view.tag inSection:0];
        
        [self.collectionView deleteItemsAtIndexPaths:@[indexPath]];


}


//懒加载
- (NSMutableArray *)favoriteList{
    if (_favoriteList == nil) {
        
        NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        
        NSString *filePath = [docPath stringByAppendingPathComponent:@"favorite.archieve"];
        
        _favoriteList = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
    }
    
//    NSLog(@"%zd",_favoriteList.count);
    
    return _favoriteList;
}





@end
